﻿using System.Collections;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace Tools.PostProcess
{
    public class PostProceControl : MonoBehaviour
    {
        private Volume m_Volume;

        private Vignette m_Vignette;

        private ChromaticAberration m_ChromaticAberration;

        private void Start()
        {
            m_Volume = GameObject.FindWithTag("Volume").GetComponent<Volume>();
            if (m_Volume != null)
            {
                m_Volume.profile.TryGet<Vignette>(out m_Vignette);
                m_Volume.profile.TryGet<ChromaticAberration>(out m_ChromaticAberration);
            }
            else
            {
                Debug.Log("获取后处理配置失败！请检查场景是否有Volume，或是其标签不对");
            }
        }


        public void VignettePostProcess(AnimationCurve curve)
        {
            StartCoroutine(VignetteTransform(curve));
        }

        /// <summary>
        /// 调整晕映
        /// </summary>
        /// <param name="curve"></param>
        /// <returns></returns>
        private IEnumerator VignetteTransform(AnimationCurve curve)
        {
            float duration = curve.keys[curve.length - 1].time;
            float timer = 0f;
            while (timer < duration)
            {
                m_Vignette.intensity.value = curve.Evaluate(timer);
                timer += Time.deltaTime;
                yield return null;
            }
            m_Vignette.intensity.value = 0f;
        }

        public void ChromaticAberrationPostProcess(AnimationCurve curve)
        {
            StartCoroutine(ChromaticAberrationTransform(curve));
        }

        /// <summary>
        /// 色差调节
        /// </summary>
        /// <param name="curve"></param>
        /// <returns></returns>
        private IEnumerator ChromaticAberrationTransform(AnimationCurve curve)
        {
            float duration = curve.keys[curve.length - 1].time;
            float timer = 0f;
            while (timer < duration)
            {
                m_ChromaticAberration.intensity.value = curve.Evaluate(timer);
                timer += Time.deltaTime;
                yield return null;
            }
            m_ChromaticAberration.intensity.value = 0f;
        }
    }

}